import { cloneDeep, lodashMap as map,template as lodashTemplate } from "lodash-es";
import { failres, okres } from "../config/resUtil.js";

// 一些默认的公共的操作
@Controller("/api/<%=tableName%>")
export class UserController {
  @App("koa")
  app: Application;

  @Post("/apis")
  async apis(@Body() body) {
    var funname = body?._name;
    var func = this?.[funname];
    if (!func) {
      return failres(funname + "404");
    }

    var _params = cloneDeep(body);
    delete _params._name;
    delete _params["模块"];

    var _func = func.bind(this);
    return _func(_params);
  }


    async querybuildcomon(query,body){
        query.where('1','=','1');
       <% _.map(colkeys,keyitem=>{ %>
        if (body?.['<%=keyitem.Field%>']) {
            query.andWhere("<%=keyitem.Field%>", body?.['<%=keyitem.Field%>']);
        }
        <% }) %>

      
    }



  async getlist(body) {
    console.log("开始 列表 ");

    var query = this.app.db.select().from("<%=tableName%>");

//获取默认字段
this.querybuildcomon(query,body);
   
    return okres(await query);
  }

  async getbyitem(body) {
    console.log("开始 获取单个 ");
    var query = this.app.db.select("*").from("<%=tableName%>");
    console.log("body :", body);


    if(body?.id){
        return okres(null);
}

    if ((!body) || !Object.keys(body).length) {
      return okres(null);
    }

    if (body?.id) {
      query.where("id", body?.id);
    } else {
     
    }


    console.log("query :", query);

    var lists = await query;
    var one = lists?.[0];

    return okres(one);
  }

  async 删除(body) {
  if(!body.id){
  return failres('没有id')
  }
    var delresult = await this.app.db('<%=tableName%>').where('id', body.id).del();
    return okres(delresult);
  }

  async addorupdate(body) {
    console.log("开始 新增or修改 ");
    var rsiltonme = await this.getbyitem(body);
    var one = rsiltonme && rsiltonme.data;
    console.log("one :", one);

    var result = undefined;
    if (one?.id) {
      var __params=cloneDeep(body)
      delete __params.id
      result = await this.app.db("<%=tableName%>").where("id", '=',one.id).update(__params);
    } else {
      // 新增
      result = await this.app.db("<%=tableName%>").insert(body);
    }
    return okres(result);
  }